package com.vnp.vchat.version2;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.animation.Animation;
import android.widget.ImageButton;
import android.widget.TextView;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;
import com.google.android.gcm.GCMRegistrar;
import com.telpoo.frame.model.BaseModel;
import com.telpoo.frame.model.BaseTask;
import com.telpoo.frame.model.TaskListener;
import com.telpoo.frame.net.BaseNetSupportBeta;
import com.telpoo.frame.net.NetConfig;
import com.telpoo.frame.ui.BaseActivity;
import com.telpoo.frame.ui.BetaBaseActivity;
import com.telpoo.frame.utils.Mlog;
import com.vnp.vchat.MainPanelActivity;
import com.vnp.vchat.R;
import com.vnp.vchat.bean.ObjKhachhang;
import com.vnp.vchat.database.DBAdapter;
import com.vnp.vchat.database.DBFunction;
import com.vnp.vchat.task.Task;
import com.vnp.vchat.task.TaskType;
import com.vnp.vchat.util.Common;
import com.vnp.vchat.util.PreferenceHelper;
import com.vnp.vchat.util.Utils;

public class SplashScreenActivity extends BetaBaseActivity implements TaskType {
	PreferenceHelper preferenceHelper;
	TextView txtCopyRight, txtTilteDangnhap;
	ImageButton btnLoginVatgia, btnLoginFb;

	String sendId = "";
	Handler mHandler = new Handler();
	Animation lefInAnimation, rightInAnimation, fadeIn;

	Runnable rMain = new Runnable() {

		@Override
		public void run() {
			gotoMain();
		}
	};

	Runnable rLogin = new Runnable() {

		@Override
		public void run() {
			gotoLogin();
		}
	};

	private BroadcastReceiver mReceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash_screen);
		BaseNetSupportBeta.getInstance().init(new NetConfig.Builder().contentType("application/x-www-form-urlencoded").build());

		Tracker tracker = GoogleAnalytics.getInstance(this).getTracker("UA-56271183-1");

		HashMap<String, String> hitParameters = new HashMap<String, String>();
		hitParameters.put(Fields.HIT_TYPE, "appview");
		hitParameters.put(Fields.SCREEN_NAME, "Home Screen");

		tracker.send(hitParameters);

		Mlog.isLog = true;
		preferenceHelper = new PreferenceHelper(this);
		registerGCM();
		txtCopyRight = (TextView) findViewById(R.id.txt_copyright);
		txtTilteDangnhap = (TextView) findViewById(R.id.txt_title_dangnhap);

		btnLoginVatgia = (ImageButton) findViewById(R.id.btn_login_vatgia);
		btnLoginFb = (ImageButton) findViewById(R.id.btn_login_fb);
		// xu ly link

		Intent intent = getIntent();
		Uri urllink = intent.getData();

		if (urllink != null) {

			try {
				int tem1 = urllink.toString().indexOf("use_id=");
				sendId = urllink.toString().substring(tem1 + 7);
				Common.idVchat = sendId;
				// sendIdToServer(sendId);

			} catch (Exception e) {
			}

		}

		setFont();

		if (preferenceHelper.getUserId().equals("") || preferenceHelper.getUserId().equals(null)) { // chua
																									// dang
																									// nhap
			mHandler.removeCallbacks(rLogin);
			mHandler.postDelayed(rLogin, 1000);
		} else { // da dang nhap

			if (sendId != null && sendId.length() > 0) { // nhay tu web vao
				// lay chatid
				ArrayList<String> list = new ArrayList<String>();
				list.add(preferenceHelper.getUserId());
				list.add(sendId);
				list.add(preferenceHelper.getHash());
				Task task = new Task(model, TASK_VGID2CHATID, list, SplashScreenActivity.this);
				task.exe();

			} else {

				mHandler.removeCallbacks(rMain);
				mHandler.postDelayed(rMain, 1000);
			}
		}

		DBFunction dbf = new DBFunction(DBAdapter.getObj(this));
		dbf.getContactSV();
		recivedBroadcast();

	}

	private void recivedBroadcast() {
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("com.package.FINISH");

		mReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				finish();
			}
		};
		// register
		this.registerReceiver(mReceiver, intentFilter);
	}

	private void setFont() {
		txtCopyRight.setTypeface(Utils.getTypefaceLight(SplashScreenActivity.this));
		txtTilteDangnhap.setTypeface(Utils.getTypefaceLight(SplashScreenActivity.this));
	}

	private void gotoMain() {
		Intent t = new Intent(SplashScreenActivity.this, MainPanelActivity.class);
		finish();
		startActivity(t);
	}

	private void gotoLogin() {
		Intent t = new Intent(SplashScreenActivity.this, GetAccountByPhoneOrEmailActivity.class);
		finish();
		startActivity(t);
	}

	void registerGCM() {
		try {
			// if (Build.FINGERPRINT.startsWith("generic")) {
			// // running on an emulator
			// Log.e("EMULATOR", "======================");
			// } else {
			// running on a device
			// Make sure the device has the proper dependencies.
			GCMRegistrar.checkDevice(SplashScreenActivity.this);

			// Make sure the manifest was properly set - comment out this line
			// while developing the app, then uncomment it when it's ready.
			GCMRegistrar.checkManifest(SplashScreenActivity.this);

			String regId = GCMRegistrar.getRegistrationId(SplashScreenActivity.this);

			// Check if regid already presents
			if (regId.equals("")) {
				GCMRegistrar.register(this, Common.PROJECT_NUMBER);
			}

			new Thread(new Runnable() {

				@Override
				public void run() {
					String regId = "";

					while (regId.equals("")) {
						regId = GCMRegistrar.getRegistrationId(SplashScreenActivity.this);
						Log.i("vChat", "Registered with id " + regId);
						preferenceHelper.setDeviceId(regId);
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}).start();
			// }
		} catch (Exception e) {
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// unregisterReceiver(mReceiver);
		mHandler.removeCallbacks(rMain);
		mHandler.removeCallbacks(rLogin);
		mHandler.removeCallbacksAndMessages(null);
		// System.exit(0);
		Log.i("vChat", "ON destroy");
	}

	@Override
	protected void onStop() {
		super.onStop();
		EasyTracker.getInstance(SplashScreenActivity.this).activityStop(SplashScreenActivity.this);
	}

	@Override
	public void onSuccess(int taskType, ArrayList<?> list, String msg) {
		super.onSuccess(taskType, list, msg);
		gotoMain();

	}

	@Override
	public void onFail(int taskType, String msg) {
		super.onFail(taskType, msg);
		showToast("" + msg);
		gotoMain();
	}

}
